//
//  UUIntentOrderHistoryListVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 01/03/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUIntentOrderHistoryListVC.h"
#import "UUIntentOrderManager.h"
#import "UUBaseTableViewCell.h"
#import "UUIntentOrderDetailVC.h"

@interface UUIntentOrderHistoryCell : UUBaseTableViewCell

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UILabel *daysLabel;
@property (nonatomic, strong) UILabel *arrivalLabel;
@property (nonatomic, strong) UILabel *carNumberLabel;
@property (nonatomic, strong) UILabel *statusLabel;

@end

@implementation UUIntentOrderHistoryCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.titleLabel = [UILabel new];
        self.titleLabel.font = [UIFont systemFontOfSize:15];
        self.titleLabel.textColor = COMMON_TEXT_DARK_PURPLE_COLOR;
        [self.contentView addSubview:self.titleLabel];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(21);
            make.top.mas_equalTo(18);
            make.left.mas_equalTo(15);
        }];
        
        self.timeLabel = [UILabel new];
        [self.contentView addSubview:self.timeLabel];
        [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.titleLabel);
            make.top.equalTo(self.titleLabel.mas_bottom).offset(9);
            make.height.mas_equalTo(26);
        }];
        self.daysLabel = [UILabel new];
        [self.contentView addSubview:self.daysLabel];
        [self.daysLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.timeLabel);
            make.top.equalTo(self.timeLabel.mas_bottom);
            make.height.equalTo(self.timeLabel);
        }];
        self.arrivalLabel = [UILabel new];
        [self.contentView addSubview:self.arrivalLabel];
        [self.arrivalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-15);
            make.left.equalTo(self.contentView.mas_centerX).offset(20);
            make.height.equalTo(self.timeLabel);
            make.top.equalTo(self.timeLabel);
        }];
        self.carNumberLabel = [UILabel new];
        [self.contentView addSubview:self.carNumberLabel];
        [self.carNumberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.arrivalLabel);
            make.height.equalTo(self.timeLabel);
            make.top.equalTo(self.daysLabel);
        }];
        
        self.statusLabel = [UILabel new];
        self.statusLabel.font = [UIFont systemFontOfSize:14];
        [self.contentView addSubview:self.statusLabel];
        [self.statusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(13);
            make.right.mas_equalTo(-15);
            make.height.mas_equalTo(20);
        }];
    }
    
    return self;
}

- (void)setupWithModel:(UUIntentOrderHistoryModel *)model {
    self.titleLabel.text = [GetCarCategoryManager() fetchCarCategoryWithCategoryId:model.carCategoryId].name;
    
    self.timeLabel.attributedText = [self generateAttributedStringWithTitle:@"时间：" text:[model.departTime formatDateByFormatString:@"yyyy.MM.dd HH:mm"]];
    self.arrivalLabel.attributedText = [self generateAttributedStringWithTitle:@"到达城市：" text:[GetCityManager() fetchCityWithCityId:model.arrival.toAddressModel.cityId].simpleName];
    self.daysLabel.attributedText = [self generateAttributedStringWithTitle:@"天数：" text:[NSString daysToDisplayString:model.days]];
    self.carNumberLabel.attributedText = [self generateAttributedStringWithTitle:@"数量：" text:[NSString stringWithFormat:@"%ld辆", model.carNum]];
    
    switch (model.status) {
        case UUIntentOrderStatusInvalid:
            self.statusLabel.text = @"已失效";
            self.statusLabel.textColor = COMMON_TEXT_LIGHT_COLOR;
            break;
        case UUIntentOrderStatusCompleted:
            self.statusLabel.text = @"已成交";
            self.statusLabel.textColor = COMMON_TEXT_GREEN_COLOR;
            break;
        case UUIntentOrderStatusProcessing:
            self.statusLabel.text = @"";
            break;
    }
}

- (NSAttributedString *)generateAttributedStringWithTitle:(NSString *)title text:(NSString *)text {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:title attributes:@{
                                                                                                                       NSFontAttributeName : [UIFont systemFontOfSize:14],
                                                                                                                       NSForegroundColorAttributeName : COMMON_TEXT_LIGHT_COLOR
                                                                                                                       }];
    [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:text attributes:@{
                                                                                                          NSFontAttributeName : [UIFont systemFontOfSize:14],
                                                                                                          NSForegroundColorAttributeName : COMMON_TEXT_BLACK_COLOR
                                                                                                          }]];
    return attributedString;
}

@end

/////////////////////////////////////////////////////////////////////////////////

#define PAGE_LENGTH     (20)

@interface UUIntentOrderHistoryListVC ()

@property (nonatomic, strong) NSMutableArray<NSNumber *> *orders;
@property (nonatomic, strong) id since;

@end

@implementation UUIntentOrderHistoryListVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"历史";
    
    [self.tableView registerClass:[UUIntentOrderHistoryCell class] forCellReuseIdentifier:@"Cell"];
    self.tableView.rowHeight = 130;
    self.tableView.estimatedRowHeight = 0;
    
    ShowIndicator();
    WEAK_SELF();
    [GetIntentOrderManager() asyncFetchIntentOrderHistoryLisWithSince:nil
                                                               length:PAGE_LENGTH
                                                        completeBlock:^(NSArray<NSNumber *> *orders, id since, NSError *error) {
                                                            HideIndicatorInView(weakSelf.view);
                                                            
                                                            if (error == nil) {
                                                                weakSelf.since = since;
                                                                weakSelf.orders = [orders mutableCopy];
                                                                [weakSelf.tableView reloadData];
                                                                
                                                                weakSelf.tableView.mj_footer.hidden = orders.count < PAGE_LENGTH;
                                                            } else {
                                                                ShowTipsOnView(error.localizedDescription, weakSelf.view);
                                                            }
                                                        }];
    
    self.tableView.mj_footer = [UURefreshFooter footerWithRefreshingBlock:^{
        [weakSelf loadMore];
    }];
    self.tableView.mj_footer.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadMore {
    WEAK_SELF();
    [GetIntentOrderManager() asyncFetchIntentOrderHistoryLisWithSince:weakSelf.since
                                                               length:PAGE_LENGTH
                                                        completeBlock:^(NSArray<NSNumber *> *orders, id since, NSError *error) {
                                                            if (error == nil) {
                                                                weakSelf.since = since;
                                                                [weakSelf.orders addObjectsFromArray:orders];
                                                                [weakSelf.tableView reloadData];
                                                                
                                                                if (orders.count < PAGE_LENGTH) {
                                                                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                                                                    weakSelf.tableView.mj_footer.hidden = YES;
                                                                } else {
                                                                    [weakSelf.tableView.mj_footer endRefreshing];
                                                                }
                                                            } else {
                                                                [weakSelf.tableView.mj_footer endRefreshing];
                                                                ShowTipsOnView(error.localizedDescription, weakSelf.view);
                                                            }
                                                        }];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.orders.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UUIntentOrderHistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    NSNumber *orderId = self.orders[indexPath.row];
    
    UUIntentOrderHistoryModel *order = [GetIntentOrderManager() fetchIntentHistoryOrderWithOrderId:orderId];
    [cell setupWithModel:order];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSNumber *orderId = self.orders[indexPath.row];
    
    UUIntentOrderDetailVC *orderDetailVC = [UUIntentOrderDetailVC instanceOfAppropriate];
    orderDetailVC.intentOrderId = orderId;
    [self.navigationController pushViewController:orderDetailVC animated:YES];

}

@end
